package com.sunny.cloudgateway;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Configuration
public class Config {

    /**
     * gateway限流规则，根据请求参数中的 user 字段来限流
     *  也可以设置根据请求 IP 地址、uri等来限流
     */
    @Bean
    KeyResolver userKeyResolver() {
        //使用user参数值限流
        return exchange -> Mono.just(Objects.requireNonNull(exchange.getRequest().getQueryParams().getFirst("user")));
        // 使用uri限流
//        return exchange -> Mono.just(exchange.getRequest().getPath().value());
        //使用ip地址限流
//        return exchange -> Mono.just(Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getHostName());
    }
}